import jsTool
import Image
import math


def aver(k):
    i=0
    sumNum=0
    average=0
    for kk in k:

        sumNum+=kk
        average+=i*kk
        i+=1
    if sumNum!=0:
        return average/sumNum
    else :
        return 0

def getColor(ii):
    h=ii.histogram()
    r=h[:256]
    g=h[256:512]
    b=h[512:768]
    return [aver(r),aver(g),aver(b)]

def analysisPic(filename,subPicNum):
    print 'analysisPic'
    im = Image.open(filename)

    picNum=subPicNum
    '''size of target pic'''
    x,y = im.size

    print 'size of target pic',x,y
    '''xpic*ypic source pics to complete the target pic'''
    xpic ,ypic = int(math.sqrt(picNum*(x+0.0)/y)),int(math.sqrt(picNum*(y+0.0)/x))
    print 'subPicNum : ',xpic,ypic
    cropInterval =xsize=x/xpic
    print 'interval', cropInterval
    bitmap =[]
    starty=0
    j=0
    for yflag in range (0,ypic):
        startx=0
        linemap=[]
        i=0
        print j ,'/',ypic
        for xflag in range (0, xpic):
  
            #print i,j,(startx,starty,startx+cropInterval,starty+cropInterval),
            iim = im.crop((startx,starty,startx+cropInterval,starty+cropInterval))
            
            #print (startx,starty),
            #print getColor(iim),
            color = getColor(iim)
            #print color
            linemap.append(color)

            i+=1

            startx=(x*i)/xpic

        #print ''
        j+=1
        starty=(y*j)/ypic
        bitmap.append(linemap)
        
    iim=im.crop((0,0,xpic,xpic))
    #print getColor(iim)
    print '_________________________________________________________________'
    return bitmap
if __name__=='__main__':
    print '_________________________________________________________________'
    bitmap= analysisPic('nilin.jpg',5000)
    #print bitmap
    print len(bitmap)
    print bitmap
    
